package com.adjaisd.scarecrow.controller;


import com.adjaisd.scarecrow.common.result.Result;
import com.adjaisd.scarecrow.common.utils.jwt.JwtUtils;
import com.adjaisd.scarecrow.common.utils.mqtt.EmqClient;
import com.adjaisd.scarecrow.entity.DeviceGps;
import com.adjaisd.scarecrow.service.DeviceGpsService;
import com.adjaisd.scarecrow.service.DeviceService;
import com.adjaisd.scarecrow.vo.DeviceGpsVO;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author adjaisd
 * @since 2022-03-22
 */
@RestController
@RequestMapping("/device-gps")
public class DeviceGpsController {

    @Autowired
    EmqClient emqClient;

    @Autowired
    DeviceGpsService deviceGpsService;

    @ApiOperation(value = "更新设备GPS")
    @ApiImplicitParam(name = "map", required = true, value = "设备gps信息", paramType = "body", dataType = "json")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public Result updateGPS(HttpServletRequest request, @RequestBody Map<String, String> map) {
        try {
            Long number = Long.valueOf(map.get("number"));  // 设备号
            Double lat = Double.valueOf(map.get("lat"));    // 纬度
            Double lon = Double.valueOf(map.get("lon"));    // 经度
            long time = new Date().getTime();
            DeviceGps deviceGps = new DeviceGps(null, number, lon, lat, time);
            if (deviceGpsService.updateDeviceGPS(deviceGps))
                return Result.succ().code(200).message("更新GPS成功");
            else return Result.fail().code(400).message("更新GPS失败");
        } catch (Exception e) {
            System.out.println(e);
            return Result.fail().code(400).message("缺少必要参数");
        }
    }

    @ApiOperation(value = "获取所有设备GPS定位信息")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public Result getAllGps(HttpServletRequest request) {
        String token = request.getHeader("X-token");
        Claims claims = JwtUtils.getMembers(token);
        long userId = Long.parseLong(claims.get("id").toString());

        DeviceGpsVO allDeviceGps = deviceGpsService.getAllDeviceGps(userId);
        return Result.succ().code(200).data("gps", allDeviceGps).message("查询设备GPS信息成功");
    }

}
